package io.renren.modules.app.controller;


import io.renren.common.annotation.SysLog;
import io.renren.common.utils.ConstantLocal;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.app.form.LoginForm;
import io.renren.modules.app.utils.JwtUtils;
import io.renren.modules.generator.entity.BsnMentorEntity;
import io.renren.modules.generator.entity.BsnStudentEntity;
import io.renren.modules.generator.service.BsnMentorService;
import io.renren.modules.generator.service.BsnStudentService;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysConfigService;
import io.renren.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * APP登录授权
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-23 15:31
 */
@RestController
@RequestMapping("/app")
@Api("APP登录接口")
public class AppLoginController {
    @Autowired
    private JwtUtils jwtUtils;

	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private SysConfigService sysConfigService;
	
    @Autowired
    private BsnMentorService bsnMentorService;
    @Autowired
    private BsnStudentService bsnStudentService;
    
    /**
     * 登录
     */
    @SysLog("APP登录")
    @PostMapping("login")
    @ApiOperation("登录")
    public R login(@RequestBody LoginForm form){
        //表单校验
        ValidatorUtils.validateEntity(form);

		//用户信息
		SysUserEntity user = sysUserService.queryByMobile(form.getMobile());

		if (user == null) {
			return R.error("账号不存在");
		}
		//账号不存在、密码错误
		if(!user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
			return R.error("密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0){
			return R.error("账号已被锁定,请联系管理员");
		}

        //生成token
        String token = jwtUtils.generateToken(user.getUserId());

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());
        ClientUserInfo clientUserInfo = new ClientUserInfo();
        clientUserInfo.userType = user.getUserType();
        clientUserInfo.showUserName = user.getUsername();
        clientUserInfo.xingb = getXingb(user.getUserType(), 
        		user.getUserId().toString());

        map.put("userInfo", clientUserInfo);
        return R.ok(map);
    }

    /**
     * 登录
     */
    @RequestMapping("version")
    public R version(@RequestParam String platform){
    	if (StringUtils.isBlank(platform)) {
    		return R.error("platform参数必填");
    	}
    	R r = R.ok();
    	String version = "";
    	if (platform.equals("android")) {
    		version = sysConfigService.getValue("android-version");
    	} else if (platform.equals("ios")) {
    		version = sysConfigService.getValue("ios-version");
    	} else {
    		return R.error("platform参数无效");
    	}
		r.put("version", version);
		r.put("content", "发现新版本: " + version + "，请及时更新！");
		r.put("androidApkUrl", sysConfigService.getValue("android-apk-url"));
		r.put("iosIpaUrl", sysConfigService.getValue("ios-ipa-url"));
		return r;
    }
    
    private String getXingb(String userType, String userId) {
    	String ret = "";
    	if (ConstantLocal.USER_TYPE_MENTOR.equals(userType)) {
    		BsnMentorEntity mentor = bsnMentorService.selectByLoginId(userId);
    		if (mentor != null) {
    			ret = mentor.getXingb();
    		}
    	} else if(ConstantLocal.USER_TYPE_PARENT.equals(userType)) {
    		BsnStudentEntity student = bsnStudentService.selectByLoginId(userId);
			if (student != null) {
				ret = student.getXingb();
			}    	   
    	}
    	return ret;
    	
    }
    
    /**
     * 给客户端，登录信息使用
     */
    public class ClientUserInfo {
    	public String userType;
    	public String showUserName;
    	public String xingb;
    	public String touxiangUrl;
    }
}
